import { logDataCache, dumpPathCache, componentCache } from '../utils/cacheManager'
import { useFileDataStore } from '../stores/fileData'
import { useDumpStore } from '../stores/dumps'
// import { useWorkspaceStore } from '../stores/workspace'
import { getDumpLogData } from '../utils/archiveDb'
import { LOG_PATHS } from '../config/logPaths'

// 数据加载优先级
export enum LoadPriority {
  IMMEDIATE = 0,  // 立即加载
  HIGH = 1,       // 高优先级
  NORMAL = 2,     // 普通优先级
  LOW = 3,        // 低优先级
  BACKGROUND = 4  // 后台加载
}

// 数据类型定义
export interface LogData {
  content: string
  size: number
  timestamp: number
  source: string
}

export interface ComponentInfo {
  name: string
  hasLogs: boolean
  logCount: number
  lastUpdate: number
}

export interface DumpFileInfo {
  path: string
  size: number
  extracted: boolean
  included: boolean
}

/**
 * 智能数据加载服务
 * 实现懒加载、预加载、优先级队列等功能
 */
export class DataLoaderService {
  private loadingQueue: Map<string, LoadPriority> = new Map()
  private loadingPromises: Map<string, Promise<any>> = new Map()
  private isProcessingQueue = false
  private _fileDataStore: any = null
  private _dumpStore: any = null
  // private _workspaceStore: any = null

  private get fileDataStore() {
    if (!this._fileDataStore) {
      this._fileDataStore = useFileDataStore()
    }
    return this._fileDataStore
  }

  private get dumpStore() {
    if (!this._dumpStore) {
      this._dumpStore = useDumpStore()
    }
    return this._dumpStore
  }

  // private get _workspaceStore_unused() {
  //   if (!this._workspaceStore) {
  //     this._workspaceStore = useWorkspaceStore()
  //   }
  //   return this._workspaceStore
  // }

  constructor() {
    this.startBackgroundProcessor()
  }

  /**
   * 预加载关键数据
   */
  async preloadCriticalData(workspaceId: string): Promise<void> {
    console.log(`[DataLoader] 开始预加载工作区 ${workspaceId} 的关键数据`)
    
    const tasks = [
      this.loadDirectoryStructure(workspaceId, LoadPriority.IMMEDIATE),
      this.loadComponentList(workspaceId, LoadPriority.IMMEDIATE),
      this.loadDumpFilePaths(workspaceId, LoadPriority.HIGH)
    ]

    await Promise.allSettled(tasks)
    console.log(`[DataLoader] 工作区 ${workspaceId} 关键数据预加载完成`)
  }

  /**
   * 懒加载日志数据
   */
  async loadLogData(workspaceId: string, logType: string, _priority: LoadPriority = LoadPriority.NORMAL): Promise<LogData | null> {
    const cacheKey = `log_${workspaceId}_${logType}`
    
    // 检查缓存
    const cached = logDataCache.get<LogData>(cacheKey)
    if (cached) {
      console.log(`[DataLoader] 从缓存获取日志数据: ${logType}`)
      return cached
    }

    // 检查是否正在加载
    if (this.loadingPromises.has(cacheKey)) {
      return this.loadingPromises.get(cacheKey)!
    }

    // 创建加载任务
    const loadPromise = this.executeLogDataLoad(workspaceId, logType)
    this.loadingPromises.set(cacheKey, loadPromise)

    try {
      const result = await loadPromise
      if (result) {
        logDataCache.set(cacheKey, result, { persist: true })
      }
      return result
    } finally {
      this.loadingPromises.delete(cacheKey)
    }
  }

  /**
   * 加载组件日志数据
   */
  async loadComponentLogs(workspaceId: string, componentName: string, priority: LoadPriority = LoadPriority.NORMAL): Promise<string[]> {
    const cacheKey = `component_${workspaceId}_${componentName}`
    
    // 检查缓存
    const cached = componentCache.get<string[]>(cacheKey)
    if (cached) {
      console.log(`[DataLoader] 从缓存获取组件日志: ${componentName}`)
      return cached
    }

    // 添加到加载队列
    this.addToQueue(cacheKey, priority)
    
    // 如果是高优先级，立即处理
    if (priority <= LoadPriority.HIGH) {
      return this.executeComponentLogLoad(workspaceId, componentName)
    }

    // 等待队列处理
    return new Promise((resolve) => {
      const checkInterval = setInterval(() => {
        const result = componentCache.get<string[]>(cacheKey)
        if (result) {
          clearInterval(checkInterval)
          resolve(result)
        }
      }, 100)
    })
  }

  /**
   * 加载转储文件路径
   */
  async loadDumpFilePaths(workspaceId: string, _priority: LoadPriority = LoadPriority.NORMAL): Promise<DumpFileInfo[]> {
    const cacheKey = `dump_paths_${workspaceId}`
    
    // 检查缓存
    const cached = dumpPathCache.get<DumpFileInfo[]>(cacheKey)
    if (cached) {
      console.log(`[DataLoader] 从缓存获取转储文件路径`)
      return cached
    }

    const result = await this.executeDumpPathLoad(workspaceId)
    if (result) {
      dumpPathCache.set(cacheKey, result, { persist: true })
    }
    return result || []
  }

  /**
   * 加载目录结构
   */
  async loadDirectoryStructure(workspaceId: string, _priority: LoadPriority = LoadPriority.NORMAL): Promise<any> {
    const cacheKey = `directory_${workspaceId}`
    
    // 检查缓存
    const cached = logDataCache.get(cacheKey)
    if (cached) {
      console.log(`[DataLoader] 从缓存获取目录结构`)
      return cached
    }

    const fileData = this.fileDataStore.getFileData(workspaceId)
    if (!fileData) return null

    // 解析目录结构
    const structure = this.parseDirectoryStructure(fileData)
    logDataCache.set(cacheKey, structure, { persist: true })
    
    return structure
  }

  /**
   * 加载组件列表
   */
  async loadComponentList(workspaceId: string, _priority: LoadPriority = LoadPriority.NORMAL): Promise<ComponentInfo[]> {
    const cacheKey = `components_${workspaceId}`
    
    // 检查缓存
    const cached = componentCache.get<ComponentInfo[]>(cacheKey)
    if (cached) {
      console.log(`[DataLoader] 从缓存获取组件列表`)
      return cached
    }

    const result = await this.executeComponentListLoad(workspaceId)
    if (result) {
      componentCache.set(cacheKey, result, { persist: true })
    }
    return result || []
  }

  /**
   * 加载组件版本信息
   */
  async loadComponentVersionInfo(workspaceId: string, _priority: LoadPriority = LoadPriority.NORMAL): Promise<string | null> {
    const cacheKey = `version_info_${workspaceId}`
    
    // 检查缓存
    const cached = logDataCache.get<LogData>(cacheKey)
    if (cached) {
      console.log(`[DataLoader] 从缓存获取组件版本信息`)
      return cached.content
    }

    const result = await this.executeVersionInfoLoad(workspaceId)
    if (result) {
      logDataCache.set(cacheKey, {
        content: result,
        size: result.length,
        timestamp: Date.now(),
        source: 'package_info'
      }, { persist: true })
      return result
    }
    return null
  }

  /**
   * 预加载转储数据
   */
  async preloadDumpData(workspaceId: string, dumpType: 'framework' | 'operation' | 'app'): Promise<void> {
    const includedPaths = this.dumpStore.getIncludedPaths(workspaceId, dumpType === 'app' ? 'debug' : dumpType)
    
    console.log(`[DataLoader] 开始预加载 ${dumpType} 转储数据，包含 ${includedPaths.length} 个文件`)
    
    const loadTasks = includedPaths.map(async (path: string) => {
      const indexMatch = path.match(/\.(\d+)\.gz$/)
      if (indexMatch) {
        const dumpIndex = parseInt(indexMatch[1])
        const cacheKey = `dump_${workspaceId}_${dumpType}_${dumpIndex}`
        
        if (!logDataCache.has(cacheKey)) {
          try {
            const data = await getDumpLogData(workspaceId, dumpType, dumpIndex)
            if (data) {
              logDataCache.set(cacheKey, {
                content: data,
                size: data.length,
                timestamp: Date.now(),
                source: `dump_${dumpType}_${dumpIndex}`
              }, { persist: true })
            }
          } catch (error) {
            console.warn(`[DataLoader] 预加载转储数据失败: ${path}`, error)
          }
        }
      }
    })

    await Promise.allSettled(loadTasks)
    console.log(`[DataLoader] ${dumpType} 转储数据预加载完成`)
  }

  /**
   * 清理工作区缓存
   */
  clearWorkspaceCache(workspaceId: string): void {
    const patterns = [
      `log_${workspaceId}_`,
      `component_${workspaceId}_`,
      `dump_paths_${workspaceId}`,
      `directory_${workspaceId}`,
      `components_${workspaceId}`,
      `dump_${workspaceId}_`
    ]

    patterns.forEach(pattern => {
      [logDataCache, componentCache, dumpPathCache].forEach(_cache => {
        // 这里需要实现按模式删除的功能
        // 暂时使用遍历方式
        // const _stats = cache.getStats()
        console.log(`[DataLoader] 清理工作区 ${workspaceId} 的缓存，模式: ${pattern}`)
      })
    })
  }

  /**
   * 获取缓存统计信息
   */
  getCacheStats() {
    return {
      logData: logDataCache.getStats(),
      component: componentCache.getStats(),
      dumpPath: dumpPathCache.getStats()
    }
  }

  // 私有方法

  private addToQueue(key: string, priority: LoadPriority): void {
    this.loadingQueue.set(key, priority)
    if (!this.isProcessingQueue) {
      this.processQueue()
    }
  }

  private async processQueue(): Promise<void> {
    if (this.isProcessingQueue) return
    this.isProcessingQueue = true

    try {
      while (this.loadingQueue.size > 0) {
        // 按优先级排序
        const sortedEntries = Array.from(this.loadingQueue.entries())
          .sort(([, a], [, b]) => a - b)

        const [key, priority] = sortedEntries[0]
        this.loadingQueue.delete(key)

        // 处理加载任务
        await this.processLoadTask(key, priority)
        
        // 避免阻塞UI
        await new Promise(resolve => setTimeout(resolve, 10))
      }
    } finally {
      this.isProcessingQueue = false
    }
  }

  private async processLoadTask(key: string, _priority: LoadPriority): Promise<void> {
    try {
      if (key.startsWith('component_')) {
        const [, workspaceId, componentName] = key.split('_')
        await this.executeComponentLogLoad(workspaceId, componentName)
      }
      // 可以添加其他类型的任务处理
    } catch (error) {
      console.error(`[DataLoader] 处理加载任务失败: ${key}`, error)
    }
  }

  private async executeLogDataLoad(workspaceId: string, logType: string): Promise<LogData | null> {
    try {
      const fileData = this.fileDataStore.getFileData(workspaceId)
      if (!fileData) return null

      // 根据日志类型提取相应数据
      let content = ''
      let source = logType

      switch (logType) {
        case 'operation':
          content = this.extractLogContent(fileData, LOG_PATHS.LOG_DUMP.OPERATION)
          break
        case 'framework':
          content = this.extractLogContent(fileData, LOG_PATHS.LOG_DUMP.FRAMEWORK)
          break
        case 'app':
          content = this.extractLogContent(fileData, LOG_PATHS.LOG_DUMP.APP)
          break
        default:
          return null
      }

      return {
        content,
        size: content.length,
        timestamp: Date.now(),
        source
      }
    } catch (error) {
      console.error(`[DataLoader] 加载日志数据失败: ${logType}`, error)
      return null
    }
  }

  private async executeComponentLogLoad(workspaceId: string, componentName: string): Promise<string[]> {
    try {
      const fileData = this.fileDataStore.getFileData(workspaceId)
      if (!fileData) return []

      // 提取组件日志
      const logs = this.extractComponentLogs(fileData, componentName)
      
      // 缓存结果
      const cacheKey = `component_${workspaceId}_${componentName}`
      componentCache.set(cacheKey, logs, { persist: true })
      
      return logs
    } catch (error) {
      console.error(`[DataLoader] 加载组件日志失败: ${componentName}`, error)
      return []
    }
  }

  private async executeDumpPathLoad(workspaceId: string): Promise<DumpFileInfo[]> {
    try {
      const fileData = this.fileDataStore.getFileData(workspaceId)
      if (!fileData) return []

      // 扫描转储文件路径
      const dumpFiles: DumpFileInfo[] = []
      const lines = fileData.split('\n')
      
      for (const line of lines) {
        if (line.includes('dump_info/LogDump/') && line.includes('.gz')) {
          const pathMatch = line.match(/dump_info\/LogDump\/[^\s]+\.gz/)
          if (pathMatch) {
            dumpFiles.push({
              path: pathMatch[0],
              size: 0, // 需要从实际文件获取
              extracted: true,
              included: false
            })
          }
        }
      }

      return dumpFiles
    } catch (error) {
      console.error(`[DataLoader] 加载转储文件路径失败`, error)
      return []
    }
  }

  private async executeComponentListLoad(workspaceId: string): Promise<ComponentInfo[]> {
    try {
      const fileData = this.fileDataStore.getFileData(workspaceId)
      if (!fileData) return []

      const components = new Map<string, ComponentInfo>()
      const lines = fileData.split('\n')
      
      for (const line of lines) {
        // 匹配运行日志格式
        const match = line.match(/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\.\d+\s+([a-zA-Z_][a-zA-Z0-9_]*)\s+[A-Z]+:/)
        if (match) {
          const componentName = match[1]
          if (!components.has(componentName)) {
            components.set(componentName, {
              name: componentName,
              hasLogs: true,
              logCount: 0,
              lastUpdate: Date.now()
            })
          }
          components.get(componentName)!.logCount++
        }
      }

      return Array.from(components.values()).sort((a, b) => a.name.localeCompare(b.name))
    } catch (error) {
      console.error(`[DataLoader] 加载组件列表失败`, error)
      return []
    }
  }

  private async executeVersionInfoLoad(workspaceId: string): Promise<string | null> {
    try {
      const fileData = this.fileDataStore.getFileData(workspaceId)
      if (!fileData) return null

      // 使用修复后的extractFileContent方法来获取package_info文件内容
      const { extractFileContent } = await import('../config/logPaths')
      const versionPath = 'dump_info/RTOSDump/versioninfo/package_info'
      
      const content = extractFileContent(fileData, versionPath)
      if (content) {
        console.log(`[DataLoader] 成功加载组件版本信息，内容长度: ${content.length}`)
        return content
      } else {
        console.warn(`[DataLoader] 未找到组件版本信息文件: ${versionPath}`)
        return null
      }
    } catch (error) {
      console.error(`[DataLoader] 加载组件版本信息失败`, error)
      return null
    }
  }

  private extractLogContent(fileData: string, logPath: string): string {
    // 简化的日志内容提取逻辑
    const lines = fileData.split('\n')
    const logLines: string[] = []
    
    for (const line of lines) {
      if (line.includes(logPath)) {
        logLines.push(line)
      }
    }
    
    return logLines.join('\n')
  }

  private extractComponentLogs(fileData: string, componentName: string): string[] {
    const lines = fileData.split('\n')
    const componentLogs: string[] = []
    
    for (const line of lines) {
      if (line.includes(componentName)) {
        componentLogs.push(line)
      }
    }
    
    return componentLogs
  }

  private parseDirectoryStructure(fileData: string): any {
    // 简化的目录结构解析
    const structure = {
      files: [],
      directories: [],
      totalSize: fileData.length,
      lastModified: Date.now()
    }
    
    return structure
  }

  private startBackgroundProcessor(): void {
    // 后台处理器，定期清理过期缓存和处理低优先级任务
    setInterval(() => {
      this.processQueue()
    }, 5000) // 每5秒处理一次队列
  }
}

// 全局数据加载服务实例
export const dataLoaderService = new DataLoaderService()